import requests
from  lxml import  etree

def download_pic(pic_url,button):

    response = requests.get(pic_url)
    #图片为字节流的形式,以二进制的方式写入文件
    filename = "E:/gitee  python/first test/learning_git/test/image/beautiful"+str(button)+".jpg"
    try :
        with open(filename,"wb+") as f:
            f.write(response.content)
    except:
        print("文件不存在，请确认文件名是否弄错")
def get_url(url,page):

    response = requests.get(url)
    response.encoding = "utf-8"
    return  response
def get_img(url,response):
    global button
    selector = etree.HTML(response.text)
    img_url = selector.xpath("//div[@id='thumbs']//img[@alt='loading']/@data-src")

    for i in img_url:
        load_img = download_pic(i,button)
        button += 1
        if button == 100 :
            print(button)
            break
        else:
            print(button)
            continue
button = 0
while button < 100:
    for i in range(1,7):
        page = i
        url = "https://alpha.wallhaven.cc/search?q=&categories=110&purity=100&sorting=toplist&order=asc&page="+str(page)
        try:
            responses = get_url(url, page)
        except:
            print("url 不存在 确认url是否正确")
        get_img(url,responses)

        if button == 100:
            print(button)
            break
        else:
            print(button)
            continue





